import React, { useEffect, useRef, useState } from 'react'
//在React中如果是兄弟组件通信的话，需要借助于第三方包
import PubSub from 'pubsub-js'
export default function B() {

    //创建容器对象，用来获取真实DOM
    let user = useRef();  // {current:undefined}
    let age1 = useRef();
    let sex1 = useRef();

    //初始化一个状态数据
    let [userlists, setUserLists] = useState([
        { id: 1, name: '张三', age: 18, sex: true },
        { id: 2, name: '李四', age: 19, sex: false },
        { id: 3, name: '王五', age: 20, sex: true }]);
    //当组件挂载完成之后进行频道的订阅消息
    useEffect(() => {
        //发布消息
        PubSub.publish('userlist', userlists);
        PubSub.publish('a', 100);
    }, [userlists])

    //声明一个事件函数
    let addUser = e => {
        //阻止表单提交的默认行为(通过事件对象.preventDefault())
        e.preventDefault();
        //获取表单元素值
        let name = user.current.value;
        let age = age1.current.value;
        let sex = sex1.current.value;
        // console.log(username)
        // console.log(userage)
        // console.log(usersex)
        //更新状态数据
        setUserLists([
            ...userlists,
            {
                id: userlists.length + 1,
                name,
                age,
                sex
            }
        ])
    }
    return (
        <div style={{ width: '100%', border: '1px dashed red' }}>
            <form action="http://www.baidu.com">
                <p>姓名：<input type="text" ref={user} /></p>
                <p>年龄：<input type="text" ref={age1} /></p>
                <p>性别：<select ref={sex1}>
                    <option value={true}>男</option>
                    <option value={false}>女</option>
                </select></p>
                <p><button onClick={addUser}>提交</button></p>
            </form>
        </div>
    )
}
